package rcs34.android.Namedays.Activity;

import java.util.GregorianCalendar;

import rcs34.android.Namedays.GApp;
import rcs34.android.Namedays.R;
import android.app.ListActivity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class A_Namedays extends ListActivity implements TextWatcher,
    OnItemSelectedListener {
	private ListView listView;
	private EditText searchText;
	private PersistentData m;
	private A_Namedays aThis;
	public GregorianCalendar today;

	private class PersistentData {
		public int wId;
		public NamedaysAdapter adapter = null;
		public SharedPreferences prefs;
		public String table;
		public int selectedTable = 0;
		public String filter;
		public String[] calendarTables;

		public PersistentData(Intent _intent) {
			// Intent kill = new Intent(aThis, A_Preferences.class);
			// kill.setAction(GApp.ACTION_DIE);
			// startActivity(kill);
			wId = _intent.getIntExtra(GApp.EXTRA_WID,
			    AppWidgetManager.INVALID_APPWIDGET_ID);
			prefs = GApp.getWidgetPreferences(wId);
			table = prefs.getString(getString(R.string.prefCalendar),
			    getString(R.string.dTable));
			filter = prefs.getString(getString(R.string.prefFilter), "");
			calendarTables = GApp.resources.getStringArray(R.array.calendarsValues);
			for (int i = 0; i < calendarTables.length; i++) {
				if (calendarTables[i].equals(table)) {
					selectedTable = i;
					break;
				}
			}
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return m;
	}

	// @SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		/*
		 * if (android.os.Build.VERSION.SDK_INT >= 9) { Log.w(LOGTAG,
		 * "Strict mode will be set"); android.os.StrictMode .setThreadPolicy(new
		 * android.os.StrictMode.ThreadPolicy.Builder()
		 * .detectAll().penaltyDeath().build()); android.os.StrictMode
		 * .setVmPolicy(new android.os.StrictMode.VmPolicy.Builder()
		 * .detectAll().penaltyDeath().build()); }
		 */super.onCreate(savedInstanceState);
		aThis = this;
		requestWindowFeature(Window.FEATURE_PROGRESS);
		m = (PersistentData) getLastNonConfigurationInstance();
		if (m == null) {
			m = new PersistentData(getIntent());
		}
		construct();
	}

	private void construct() {
		setContentView(R.layout.activity);
		listView = getListView();
		searchText = (EditText) findViewById(R.id.searchText);
		searchText.addTextChangedListener(this);
		searchText.setSelected(true);
		TextView emptyView = new TextView(this);
		emptyView.setText(R.string.tNoMatches);
		listView.setEmptyView(emptyView);
		Spinner spinner = (Spinner) findViewById(R.id.spinnerCalendars);
		ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter
		    .createFromResource(this, R.array.calendarsEntries,
		        android.R.layout.simple_spinner_item);
		spinnerAdapter
		    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(spinnerAdapter);
		spinner.setSelection(m.selectedTable);
		spinner.setOnItemSelectedListener(this);
		setTable(m.calendarTables[m.selectedTable]);
		searchText.setText(m.filter);
	}

	private void setTable(String _table) {
		if (m.adapter == null) {
			m.adapter = new NamedaysAdapter(this, _table);
		} else {
			m.adapter.setActivity(this);
		}
		listView.setAdapter(m.adapter);
	}

	@Override
	public void onNewIntent(Intent _intent) {
		if (m == null
		    || m.wId != _intent.getIntExtra(GApp.EXTRA_WID,
		        AppWidgetManager.INVALID_APPWIDGET_ID)) {
			m = new PersistentData(_intent);
			construct();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		today=new GregorianCalendar();
		if (m.adapter != null) {
			m.adapter.setActivity(this);
		}
		listView.invalidateViews();
		filter();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (m.adapter != null) {
			m.adapter.setActivity(null);
		}
		m.prefs.edit().putString(getString(R.string.prefFilter), m.filter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activitymain, menu);
		return true;
	}

	/*
	 * @Override public boolean onPrepareOptionsMenu(Menu menu) { return true; }
	 */

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.main_settings) {
			Intent i = new Intent(this, A_Preferences.class);
			i.putExtra(GApp.EXTRA_WID, m.wId);
			startActivity(i);
			return true;
		} else if (item.getItemId() == R.id.main_gplay) {
			openBrowser("https://play.google.com/store/apps/developer?id=rcs-34");
			return true;
		} else if (!GApp.isPro && item.getItemId() == R.id.main_pro) {
			openBrowser("https://play.google.com/store/apps/details?id=rcs34.android.NamedaysPro");
			return true;
		} else {
			return super.onOptionsItemSelected(item);
		}
	}

	private void openBrowser(String _url) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(_url));
		startActivity(i);
	}

	// @Override
	// protected void onSaveInstanceState(Bundle outState) {
	// super.onSaveInstanceState(outState);
	// outState.putString(SEARCH_TEXT, searchText.getText().toString());
	// }
	private void filter() {
		m.adapter.getFilter().filter(m.filter);
	}

	public void notifyPopulated() {
		filter();
	}

	// TextWatcher methods
	public void afterTextChanged(Editable e) {
	}

	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (!m.filter.equals(s.toString())) {
			m.filter = s.toString();
			filter();
		}
	}

	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		if (pos != m.selectedTable) {
			m.selectedTable = pos;
			m.adapter = null;
			setTable(m.calendarTables[m.selectedTable]);
		}
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
	}
}
